/* 
Copyright (c) 2004,2005, 2006, 2007, 2008 University of Illinois 

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

3. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
AccessibilityExtension.ns(function() { with (AccessibilityExtension.LIB) {

	var AE = AccessibilityExtension.ns;  
	AE.dialogName = "accessext-form-list-links";
	var linksarray = null; //AE.dataarray may have duplicates removed
	
	function linkObjectDisplayDetails() {}
	linkObjectDisplayDetails.prototype = {
		dataElementNames : ['icita07', 'icita08','order','baseuri','text','title','type','link'],
		columnHeaders : ['column.header.icita07.label', 'column.header.icita08.label','column.header.order.label','column.header.baseuri.label','column.header.linkText.label','column.header.title.label','column.header.type.label','column.header.link.label'],
		
		accessIssuesDataElementNames : ['tooshort', 'outofcontext','sameURLdiffLinks','sameLinkdiffURL', 'inCloseProxomity', 'imgTooSmall', 'altequaltextcontent'],
		accessIssuesAttrNames : ['', '','href','href', '', '', 'alt'],
		accessIssuesMessages : ['links.warnings.tooshort','links.warnings.outofcontext','links.warnings.sameURLdiffLinks','links.warnings.sameLinkdiffURL','links.warnings.inCloseProxomity','links.warnings.imgTooSmall', 'links.warnings.altequaltextcontent'],
	}
	var linkObjectDisplayDetails = new linkObjectDisplayDetails();
	
	function linkObject(torder, tnode) {
		this.order = torder;
		this.parseNode(tnode);
	}
	
	linkObject.prototype = {
		node : null,
		icita07 : "",
		icita08 : "",
		order : false,
		baseuri : '',
		id : false,
		type : "",
		text : "",
		title : "",
		rel : "",
		link : "",
		link4Cmp : "", //link for comparison purposes
		alt : "",
		nodeDocPos : null,
		tooshort : false,
		outofcontext : false,
		sameURLdiffLinks : false,
		sameLinkdiffURL : false,
		inCloseProxomity : false,
		imgTooSmall : false,
		altequaltextcontent : false,
		valid : false,
		display : true,
		displayDetails: linkObjectDisplayDetails,
		getMainColumnText : function() {
			return this.text;
		},
		parseNode : function(node) {
			try {
				this.display = true; // new duplicate removal
				this.node = node;
				this.link = this.node.href;
				this.link4Cmp = this.link.toLowerCase();
				this.link4Cmp = this.link4Cmp.replace(/\bdefault.[a-z]*|\bindex.[a-z]*/,'');
				this.id = this.node.id;
				
				this.title = GetValueFromAttributes(this.node,['title'],"");
				this.baseuri = getBaseURI(node);
				
				this.type = this.getTypeFromNode();
				this.text = getDisplayableTextRecursively(this.node);
				//search for tooshort & outofcontext errors
				if (this.text != '') {
					var tmpText = this.text.toLowerCase();
					tmpText = tmpText.replace(/\.\.\./g, '')
					if (tmpText == 'here' || tmpText == 'click' || tmpText == 'click here' || tmpText == 'more' || tmpText == 'read more') { this.outofcontext = true;}
					if (this.text.length < 4){this.tooshort = true;}
				} 
				
			   	this.nodeDocPos = accessext_getNodeDocPosition(this.node);			
				//For map elements, get the title, or if none is set, fall back on alt
				var text = "";
				if (this.node.tagName.toLowerCase() == "area") {
				//	this.text = GetValueFromAttributes(node,['title','alt'],text);
				//SMF 8/30/07 show what is found/missing
					var tmpStr = GetTitleFromNode(this.node);
					if (tmpStr != accessext_getBundleSingleString('noTitle'))
						this.text = tmpStr;
					else {	
						tmpStr =  GetAltFromNode(this.node);
						if (tmpStr != accessext_getBundleSingleString('noAlt'))
							this.text = 'alt: ' + tmpStr;
						else 
							this.text = accessext_getBundleSingleString('noAltOrTitle');
					}
					//same code as accessext_PositionHighlightNode()
					var coords = this.node.getAttribute('coords');
					if (coords != null) {
						var coordArray=coords.split(",");
						if (this.node.getAttribute('shape').toUpperCase() == 'RECT') {
							this.nodeDocPos.x = this.nodeDocPos.x + Number(coordArray[0]);
							this.nodeDocPos.y = this.nodeDocPos.y + Number(coordArray[1]);
							this.nodeDocPos.width = Number(coordArray[2]) - Number(coordArray[0]); 
							this.nodeDocPos.height = Number(coordArray[3]) - Number(coordArray[1]);  
						} else if (this.node.getAttribute('shape').toUpperCase() == 'CIRCLE') {
							this.nodeDocPos.x = this.nodeDocPos.x + Number(coordArray[0]) - Number(coordArray[2]);
							this.nodeDocPos.y = this.nodeDocPos.y + Number(coordArray[1]) - Number(coordArray[2]);
							this.nodeDocPos.width = this.nodeDocPos.height = Number(coordArray[2]) * 2; 		
						} else if (this.node.getAttribute('shape').toUpperCase() == 'POLY') {
							var xMin = coordArray[0];
							var xMax = coordArray[0];
							var yMin = coordArray[1];
							var yMax = coordArray[1];
							for (var counter = 2; counter < coordArray.length; counter += 2) {
								xMin = Math.min(coordArray[counter],xMin);
								xMax = Math.max(coordArray[counter],xMax);
								yMin = Math.min(coordArray[counter+1],yMin);
								yMax = Math.max(coordArray[counter+1],yMax);
							}
							this.nodeDocPos.x = this.nodeDocPos.x + xMin;
							this.nodeDocPos.y = this.nodeDocPos.y + yMin;
							this.nodeDocPos.width = xMax - xMin;
							this.nodeDocPos.height = yMax - yMin;		
						}
					}
				}
					
				this.alt = cleanSpaces(getDisplayableAltRecursively(this.node)); //GetAltFromNode
				if (this.alt != '' && cleanSpaces(this.node.textContent.toLowerCase()) == this.alt) {
					this.altequaltextcontent = true;
				}
				if (this.text != '') {this.text = cleanSpaces(this.text);}
				if (this.link != '') {this.link = cleanSpaces(this.link);}
				
			   if(this.node.childNodes && !this.node.textContent) {
			      for(var i=0; i<this.node.childNodes.length; i++) {
				  	if(this.node.childNodes[i].tagName) {
						if (this.node.childNodes[i].tagName.toLowerCase() == "img") {
							if (this.node.childNodes[i].clientWidth < 16 || this.node.childNodes[i].clientHeight < 16) {
								this.imgTooSmall = true;
							}
						}	
					}	
			      }
			   }
	
			} catch (ex) {
				accessext_consoleDump('parseNode exception: ' + ex);
			}
		},
		getTypeFromNode : function() {
			//accessext_consoleDump('looking up ' + this.node.href);
			if(typeof(this.node.tagName) == 'undefined') {
				return  accessext_getBundleSingleString('links.types.unknown');
			}
			
			var mapping = new Object();
			mapping['http://'] = 'links.types.http';
			mapping['https://'] = 'links.types.https';
			mapping['ftp://'] = 'links.types.ftp';
			mapping['file://'] = 'links.types.file';
			mapping['mailto:'] = 'links.types.email';
			mapping['news://'] = 'links.types.news';
		
		
			if (this.node.tagName.toLowerCase() == 'a') {
				for (var link in mapping) {
					if (this.node.href.indexOf(link) == 0) {
						return accessext_getBundleSingleString(mapping[link]);
					}
				}
				return accessext_getBundleSingleString('links.types.other');
			} else if (this.node.tagName.toLowerCase() == 'area') {
				for (var link in mapping) {
					if (this.node.href.indexOf(link) == 0) {
						return accessext_getBundleString('links.mapPrefix',accessext_getBundleSingleString(mapping[link]));
					}
				}
				return accessext_getBundleString('links.mapPrefix',accessext_getBundleSingleString('links.types.other'));
			}
			
			return  accessext_getBundleSingleString('links.types.other');
		},
		getTreeNode : function(windoc) {
			return accesxt_generateTreeboxResults(windoc,this); //,'rel'
		}
	}

AccessibilityExtension.LIB.extend(AccessibilityExtension.LIB,
{	
	newLinkObject: function(torder, tnode) { 
		var n = new linkObject(torder, tnode);
		return n; 
	},
	post_InitAccessibilityExt: function() {
		accessext_setNoteText(0);
		
		try {
			AE.treebox.addEventListener('keypress',accessext_linksSearchOnKeyPress,true);
		} catch (ex) {
			accessext_consoleDump('Failed to add onkeypress event handler: ' + ex);
		}
	},
	
	ParseDocument: function(doc) {
		ParseDocumentForLinks(doc, AE.dataarray);
		linksarray = AE.dataarray;
	},
	
	ParseDocumentForLinks: function(doc, loadArray) {
		for (var j = 0; j < doc.links.length; j++) {
			loadArray[loadArray.length] = new linkObject(loadArray.length + 1,doc.links[j]);
		}
		//Ensure that links that point to the same URL use the same link text, and that links that point to different URLs use different link text.
		for (var j = 0; j < loadArray.length; j++) {
			for (var k = j + 1; k < loadArray.length; k++) {
				if (loadArray[j].text.toLowerCase() == loadArray[k].text.toLowerCase() && loadArray[j].link4Cmp != loadArray[k].link4Cmp) {
					loadArray[j].sameLinkdiffURL = true;
					loadArray[k].sameLinkdiffURL = true;
				}
				if (loadArray[j].link4Cmp == loadArray[k].link4Cmp && loadArray[j].text.toLowerCase() != loadArray[k].text.toLowerCase()) {
					loadArray[j].sameURLdiffLinks = true;
					loadArray[k].sameURLdiffLinks = true;
				}
			}
		}
		//Ensure that links are not too close together
		for (var j = 0; j < loadArray.length; j++) {
			if (loadArray[j].tooshort || loadArray[j].imgTooSmall) {
				for (var k = j + 1; k < loadArray.length; k++) {
					if (loadArray[k].tooshort || loadArray[k].imgTooSmall) {
						var targetDepth = loadArray[j].nodeDocPos.y;
						var testDepth = loadArray[k].nodeDocPos.y;
						if (testDepth >= targetDepth-4 && testDepth <= targetDepth+4 && loadArray[j].nodeDocPos.x < loadArray[k].nodeDocPos.x) {
							var endOfCurrent = loadArray[j].nodeDocPos.x + loadArray[j].nodeDocPos.width;
							var startOfNext = loadArray[k].nodeDocPos.x;
							var twoSpWidth = 8;
							if (loadArray[j].text.length > 4 && loadArray[j].nodeDocPos.width > 0) {
								twoSpWidth = (loadArray[j].nodeDocPos.width /loadArray[j].text.length) * 2;
							}else if (loadArray[k].text.length > 4 && loadArray[k].nodeDocPos.width > 0) {
								twoSpWidth = (loadArray[k].nodeDocPos.width /loadArray[k].text.length) * 2;
							}
							if (twoSpWidth < 8) {twoSpWidth = 8;}
							if ((endOfCurrent + Math.round(twoSpWidth * .75)) > startOfNext) {
								if (startOfNext != 0) {
									loadArray[j].inCloseProxomity = true;
									loadArray[k].inCloseProxomity = true;
							//accessext_consoleDump(' twoSpWidth = ' + twoSpWidth + ' targetDepth= ' + targetDepth + ' ' + '  testDepth: ' + testDepth + ' ' + loadArray[j].order + ' endOfCurrent= ' + endOfCurrent + ' ' + loadArray[k].order +  '   startOfNext: ' + startOfNext);
								}
							}
						}
					}
				}
			}	
		}
		setMaxSeverityForArray(loadArray);
	},
	
	RemoveDuplicates: function() {
		try {
			var i,j;
			var elem = document.getElementById("checkbox-remove-duplicates");
			//Clear any selection
			AE.treebox.value = -1;
			accessext_treeboxScrollAndHighlightNode();
			AE.dataarray = new Array();
			if(elem.checked) {
				for(i=0; i < linksarray.length; i++) {
					for(j=i + 1; j<linksarray.length; j++) {
						//Instead of removing, just hide it
						if(linksarray[i].link4Cmp == linksarray[j].link4Cmp && linksarray[i].text.toLowerCase() == linksarray[j].text.toLowerCase()) {
							linksarray[j].display = false;
						} 
					}
				}		
				for(i=0; i < linksarray.length; i++) {if (linksarray[i].display == true) AE.dataarray.push(linksarray[i]);}
			} else {
				for(i=0; i < linksarray.length; i++) {linksarray[i].display = true; AE.dataarray.push(linksarray[i]);}
			}
			UpdateTreeView();
		} catch (ex) {
			accessext_consoleDump('RemoveDuplicates exception: ', ex);
		}
	},
	
	activation_custom: function(theIndex) {
		var loc = AE.dataarray[theIndex].link;
		AE.mydoc.location.href = loc;
		return true;
	},
	
	focusOnActive: function() {
		CleanUp();
		var theIndex = accessext_getActiveValue(AE.treebox);
		if (theIndex < 0 || theIndex >= AE.dataarray.length  || theIndex == null) {
			return false;
		}
		var node = AE.dataarray[theIndex].node;
		accessext_keyboardFocusNode(node,AE.thewindow);
		return true;
	},
	
	accessext_linksSearchOnKeyPress: function(e) {
		return accessext_searchOnKeyPress_common(e,AE.treebox,AE.dataarray);
	}
});
	if (AccessibilityExtension.LIB.InitAccessibilityExt) AccessibilityExtension.LIB.InitAccessibilityExt();	
}});
	